package com;

import java.io.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 监听并清除文件的只读属性
 */
public class RemoveReadOnly {

    /** 微信文件夹路径 */
    private static String folderPath = "";

    /**
     * 获取当前年月（yyyy-MM）
     */
    private static String currenMonth(){
        SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM");
        return sfd.format(new Date());
    }

    /**
     * 读取设置的路径
     */
    private static void readPath() throws IOException {
        String path = System.getProperty("user.dir");//打包用的路径：jar包或exe程序所在目录名
        InputStreamReader fReader = new InputStreamReader(new FileInputStream(path+"/微信文件夹路径.txt"),"UTF-8");
        BufferedReader reader = new BufferedReader(fReader);
        String lineTxt=null;
        while((lineTxt=reader.readLine())!=null){
            if (lineTxt.length()>0){
                folderPath = lineTxt + currenMonth();
                break;
            }
        }
    }

    /**
     * 监听文件夹，并去掉文件的只读属性
     */
    public static void removeReadOnly() throws IOException{
        File f = new File(folderPath);
        if (!f.exists()) {
            Log.msg("路径不存在，请检查 微信文件夹路径.txt 文件是否设置了路径，或设置的路径是否正确！");
        }
        // 获取文件系统的WatchService对象
        WatchService watchService = FileSystems.getDefault().newWatchService();
        // 注册监听事件
        Path dir = Paths.get(folderPath);
        dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
        while (true) { // 循环监听
            WatchKey key = null;
            try {
                key = watchService.take();
            } catch (InterruptedException e) {
                return;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) continue;
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filename = ev.context();
                File file = dir.resolve(filename).toFile();
                if (file.exists() && !file.canWrite()) { // 判断文件是否可以写入
                    file.setWritable(true); // 将文件的只读属性去掉
                    Log.msg("将文件 "+filename.toString()+" 的只读属性去掉了！");
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        try {
            readPath();
            removeReadOnly();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
